package cn.czh.system.service.impl;

import cn.czh.org.domain.Department;
import cn.czh.system.domain.Menu;
import cn.czh.system.mapper.MenuMapper;
import cn.czh.system.service.IMenuService;
import cn.czh.basic.service.impl.BaseServiceImpl;
import org.apache.velocity.runtime.directive.contrib.For;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        //1.查询所有的菜单
        List<Menu> menus = menuMapper.loadAll();
        //2.把所有查询到的菜单放到map集合中
        Map<Long, Menu> map = new HashMap<>();
        //3.遍历所有菜单
        for (Menu menu : menus){
            //4.将所有菜单装到map中
            map.put(menu.getId(),menu);
        }

        //1.前端需要获得集合数据
        List<Menu> menuTree = new ArrayList<>();
        //2.遍历数组
        for (Menu menu : menus){
            //3.如果菜单id为null就是顶级菜单
            if (menu.getParent_id()==null){
                menuTree.add(menu);
            }else { //4.不是顶级菜单
                //5.获取当前菜单的上级菜单id
               Long parent_id = menu.getParent_id();
                //6.上级菜单对象
                Menu parentMenu = map.get(parent_id);
                //7.将自己装入上级菜单的集合中
                parentMenu.getChildren().add(menu);
            }
        }
        return menuTree;
    }
}
